package br.ufrgs.dbproject.sax;

import java.io.StringWriter;

/**
 * Used to build on demand strings from a characters array.
 * 
 * @author diego
 */
public class TextBuilder {

	private boolean activated = true;

	private StringWriter builder;

	/**
	 * Creates a new instance of {@link TextBuilder} with an empty buffer.
	 */
	public TextBuilder() {
		this.builder = new StringWriter();
	}

	/**
	 * Writes into the buffer a sub sequence of the provided char array, which belongs to the range [start, start + length).
	 * 
	 * @param ch a char sequence.
	 * @param start the index of the first char to be written.
	 * @param length the number of chars that follows the first one and must be written in the buffer.
	 */
	public void write(char[] ch, int start, int length) {
		
		if (isActivated() && ch.length > 0) {

			for (int i = start; i < start + length; i++) {
				switch (ch[i]) {
				case '\\':
					builder.append("\\\\");
					break;
				case '\"':
					builder.append("\\\"");
					break;
				case '\'': // ' single quote
					builder.append("''");
					break;
				case '\n':
					builder.append("\\n");
					break;
				case '\r':
					builder.append("\\r");
					break;
				case '\t':
					builder.append("\\t");
					break;
				default:
					builder.append(ch[i]);
					break;
				}
			}
		}
	}

	/**
	 * Checks whether building process is activated or not.
	 * 
	 * @return true in case it is activated, false otherwise.
	 */
	public boolean isActivated() {
		return activated;
	}

	/**
	 * Activates the building process
	 */
	public void activate() {
		this.activated = true;
	}

	/**
	 * Deactivates the building process and clear the buffer.
	 * 
	 * <p>
	 * Any attempt to write into the buffer will be readily ignored when the building
	 * process is deactivated.
	 * </p>
	 */
	public void deactivate() {
		this.activated = false;
		builder = new StringWriter();
	}

	/**
	 * Checks whether the buffer is empty or not.
	 * @return true if the buffer is empty, false otherwise.
	 */
	public boolean isBufferEmpty() {
		return builder.getBuffer().length() == 0;
	}

	/**
	 * Gets the text built out so far.
	 * 
	 * @return the built text
	 */
	public String getText() {
		return builder.toString();
	}

}
